﻿using AhpilyServer;
using System;
using System.IO;
using ProtoBuf;
using ProtoBuf.Meta;

namespace PokerServer
{
    public class Program
    {
        // google protoBuffer 使用的一个小例子
        [ProtoContract]
        private class AccDto
        {
            [ProtoMember(1)] public readonly int id;
            [ProtoMember(2)] public readonly String name;

            // 使用这个框架需要无参构造， 可能类似反射
            public AccDto()
            {
            }

            public AccDto(int _id, String _name)
            {
                id = _id;
                name = _name;
            }
        }

        static void Main()
        {
            AccDto dto = new AccDto(1, "廖润");

            byte[] bytes = PBSSerialize(dto);
            AccDto accDto = PBDSerialize<AccDto>(bytes);

            Console.WriteLine(accDto.name);
            Console.WriteLine(accDto.id);


            // 创建一个服务器对象
            ServerPeer server = new ServerPeer();
            // 指定创建的服务器管理的应用
            server.SetApplication(new NetMsgCenter());
            // 开启服务器
            server.Start(6666, 10);

            // 设置自己的序列化方法
            // dto 层有相应的注释
            // EncodeTool.mDecodeObjDelegate = useProtoBuffer;
            // EncodeTool.mEncodingObjDelegate = PBSSerialize;

            Console.ReadKey();
        }


        private static T PBDSerialize<T>(byte[] valueBytes)
        {
            T value;

            using (MemoryStream memoryStream = new MemoryStream(valueBytes))
            {
                value = Serializer.Deserialize<T>(memoryStream);
            }

            return value;
        }

        private static byte[] PBSSerialize(object value)
        {
            byte[] buffer;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                if (value != null)
                {
                    RuntimeTypeModel.Default.Serialize(memoryStream, value);
                }

                // ProtoBuf will change the MemoryStream flag [position]
                // so need to change it[position flag] back
                memoryStream.Position = 0;

                long memoryStreamLength = memoryStream.Length;

                buffer = new byte[memoryStreamLength];

                memoryStream.Read(buffer, 0, (int) memoryStreamLength);
            }

            return buffer;
        }
    }
}